package api

import (
	"FeedXmh/app/dao"
	"FeedXmh/redis"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/xuri/excelize/v2"
	"paco_toolkit/common"
)

var Farm = farm{}

type farm struct{}

func (a *farm) GET(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()

	id := gconv.String(params["id"])
	key := gconv.String(params["key"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		model := db.Model("t_farm")
		if id != "" {
			model.Where(" id=? ", id)
		}
		if key != "" {
			model.Where(" farmname like '%?%'", key)
		}
		r, err := model.Order(" sort desc,id asc,farmname ASC ").All()
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			list := r.List()

			res["data"] = list
			res["count"] = len(list)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) PUT(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path

	params["update_date"] = gtime.Now().String()
	params["update_user"] = current_user
	id := gconv.String(params["id"])

	if dao.CheckApiPermission(url, r.Method, current_user) {
		//情况对应t_user_farm后，重新添加
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		_, err := db.Model("t_farm").Data(params).Save()
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["code"] = 0
			res["msg"] = "保存成功"
			res["data"] = id
		}

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) POST(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	_, exist := params["id"]
	if exist {
		delete(params, "id")
	}

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path
	params["create_date"] = gtime.Now().String()
	params["create_user"] = current_user
	//id:= gconv.String(params["id"])

	//db:=g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, current_user) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		re, err := db.Model("t_farm").Data(params).Save()
		if err == nil {
			newid, _ := re.LastInsertId()
			res["code"] = 0
			res["msg"] = "保存成功"
			res["data"] = newid
		} else {
			res["code"] = -1
			res["msg"] = err.Error()
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) DELETE(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	id, exist := params["id"]
	if exist {
		claims := jwt.ExtractClaims(r)
		current_user := claims["userid"].(string)
		url := r.URL.Path
		params["lpt"] = gtime.Now().String()
		params["whom"] = current_user
		//db:=g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission(url, r.Method, current_user) {
			//有单元的无法直接删除
			houses, _ := dao.T_house.GetList(fmt.Sprintf("farmid=%s", gconv.String(id)))
			if len(houses) > 0 {
				res["code"] = -1
				res["msg"] = "存在单元，无法删除"
			} else {
				_, err := dao.T_farm.Delete(gconv.String(id))
				if err != nil {
					g.Log().Line().Error(err)
					res["code"] = -1
					res["msg"] = err.Error()
				}
			}

		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	} else {
		res["code"] = -1
		res["msg"] = "错误的参数"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) Topo(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	if dao.CheckApiPermission(url, r.Method, userid) {
		var root = g.Map{
			"name":     "我的养殖场",
			"open":     true,
			"type":     "root",
			"children": nil,
		}
		//获取用户具有权限的养殖场
		//todo
		var list = g.List{}
		farm_list := dao.GetPermisFarm(userid)
		for _, v := range farm_list {
			var item = g.Map{
				"id":        v["id"],
				"farmid":    v["id"],
				"companyid": v["companyid"],
				"name":      v["farmname"],
				"open":      true,
				"type":      "farm",
				"children":  nil,
			}
			//栏舍
			house_list, err := dao.T_house.GetList(fmt.Sprintf("farmid=%s", gconv.String(v["id"])))
			if err != nil {
				g.Log().Line().Error(err)
			}
			var list1 = g.List{}
			for _, v1 := range house_list {
				var item1 = g.Map{
					"id":       v1["id"],
					"houseid":  v1["id"],
					"farmid":   v1["farmid"],
					"name":     v1["housename"],
					"open":     true,
					"type":     "house",
					"children": nil,
				}
				list1 = append(list1, item1)
			}

			item["children"] = list1
			list = append(list, item)
		}

		root["children"] = list

		res["data"] = g.List{root}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) List(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	//params := r.GetQueryMap()

	//id :=gconv.String(params["id"])
	//key :=gconv.String(params["key"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	//db:=g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		farm_list := dao.GetPermisFarm(userid)
		res["data"] = farm_list
		res["count"] = len(farm_list)
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) ListWithSummaryInfo(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	//params := r.GetQueryMap()

	//id :=gconv.String(params["id"])
	//key :=gconv.String(params["key"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	//db:=g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		farm_list := dao.GetPermisFarm(userid)
		for k, item := range farm_list {
			id := gconv.String(item["id"])
			json_str := redis.GetFarmSummary(id)
			if json_str != "" {
				summary_info := gconv.Map(json_str)
				farm_list[k]["summary_info"] = summary_info
			}
		}
		res["data"] = farm_list
		res["count"] = len(farm_list)
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

// ListByUser 上级(建立账户者)/管理员 查看下级用户具有的养殖场列表
func (a *farm) ListByUser(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()

	userid := gconv.String(params["userid"])
	//key :=gconv.String(params["key"])

	claims := jwt.ExtractClaims(r)
	cur_userid := claims["userid"].(string)
	url := r.URL.Path

	//db:=g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, cur_userid) {
		farm_list := dao.GetPermisFarm(userid)
		res["data"] = farm_list
		res["count"] = len(farm_list)
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) SummaryInfo(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	//db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		/*sql := fmt.Sprintf(`
		SELECT sum(if(mode>0,pig_num,0)) as pig_num_total,
		sum(if(mode>0,son,0)) as son_total,
		sum(if(mode=0,1,0)) as num_stop,
		sum(if(mode=1,pig_num,0)) as pig_num1,
		sum(if(mode=2,pig_num,0)) as pig_num2,
		sum(if(mode=3,pig_num,0)) as pig_num3,
		sum(if(mode=4,pig_num,0)) as pig_num4,
		sum(if(mode=5,pig_num,0)) as pig_num5,
		sum(if(mode=6,pig_num,0)) as pig_num6,
		sum(if(online=1,1,0)) as online_num,
		sum(if(online=0 || online is NULL,1,0)) as offline_num,
		sum(if(alarm>0||alarm_ext>0|| online=0 || online is NULL,1,0)) as alarm_device_num,
		sum(if(online=1,day_use_feed_auto,0)) as day_use_feed_auto,
		sum(if(online=1,day_use_feed_man,0)) as day_use_feed_man,
		sum(if(online=1,day_use_water_auto,0)) as day_use_water_auto,
		sum(if(online=1,day_use_water_man,0)) as day_use_water_man,
		sum(if(online=1,max_feed,0) ) as max_feed,
		sum(if(online=1,day_use_feed_auto+day_use_feed_man,0) ) as today_feed,
		sum(if(online=1,day_use_water_auto+day_use_water_man,0)) as today_water
		FROM v_hzgw_node WHERE farmid='%s';`, id)
				dt, err := db.GetOne(sql)
				if err != nil {
					res["code"] = -1
					res["msg"] = err.Error()
				} else {
					data := dt.Map()
					//统计栏舍和终端
					sql = fmt.Sprintf(`SELECT count(DISTINCT houseid) as house_num,count(DISTINCT device_addr) as gw_num,sum(if(alive=1,1,0)) as gw_alive_num FROM v_device WHERE farmid='%s';`, id)
					dt1, err := db.GetOne(sql)
					if err != nil {
						g.Log().Line().Error(err)
					} else {
						data1 := dt1.Map()
						data["house_num"] = data1["house_num"]
						data["gw_num"] = data1["gw_num"]
						data["gw_alive_num"] = data1["gw_alive_num"]
					}
					//昨日下料，昨日下水
					yestoday := gtime.Now().AddDate(0, 0, -1).Format(common.DATE_FORMAT)
					sql = fmt.Sprintf(`SELECT sum(day_use_feed_auto+day_use_feed_man) AS feed
				,SUM(day_use_water_auto+day_use_water_man) as water
				FROM t_hzfgw_node_status_his
				WHERE addr in (SELECT device_addr FROM v_device WHERE farmid='%s') and his_date='%s';`, id, yestoday)

					dt1, err = db.GetOne(sql)*/

		json_str := redis.GetFarmSummary(id)
		if json_str != "" {
			farm_item := gconv.Map(json_str)
			res["data"] = farm_item
		} else {
			res["code"] = -1
			res["msg"] = "无相关数据"
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) FeedHighLow(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		yestoday := gtime.Now().AddDate(0, 0, -1).Format(common.DATE_FORMAT)
		sql := fmt.Sprintf(`SELECT SUM(if(max_feed>(day_use_feed_auto+day_use_feed_man),1,0)) as low, 
       SUM(if(max_feed=(day_use_feed_auto+day_use_feed_man),1,0)) as normal , 
       SUM(if(max_feed<(day_use_feed_auto+day_use_feed_man),1,0)) as high 
FROM t_hzfgw_node_status_his WHERE mode>0 and online=1 and addr in (SELECT device_addr FROM v_device WHERE farmid='%s') 
                               and his_date='%s';`, id, yestoday)
		dt, err := db.GetOne(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			data := dt.Map()
			res["data"] = data
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) HouseSummarySort(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	farmid := gconv.String(params["farmid"])
	his_date := gconv.String(params["his_date"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		sql := fmt.Sprintf(`SELECT h.id AS houseid,h.housename,A.feed,A.water,A.max_feed,pig_num,pig_num_total,avg_feed,low_standard,standard,high_standard,day,A.per,A.his_date FROM v_house h
LEFT JOIN (
SELECT v.houseid,v.housename,
sum(day_use_feed_auto+day_use_feed_man) AS feed,
sum(day_use_water_auto+day_use_water_man) as water,
sum(max_feed) as max_feed,
sum(his.pig_num) as pig_num,
sum(his.pig_num) as pig_num_total,
avg(his.avg_feed) as avg_feed,
avg(his.low_standard) as low_standard,
avg(his.standard) as standard,
avg(his.high_standard) as high_standard,
avg(his.day) as day,
sum(day_use_feed_auto+day_use_feed_man)/sum(max_feed)*100 as per,
his.his_date as his_date 
FROM v_device v
INNER JOIN t_hzfgw_node_status_his his ON v.device_addr = his.addr and his.his_date='%s' 
WHERE v.farmid=%s and mode!=0
GROUP BY v.houseid,v.housename
ORDER BY feed desc,water desc,v.houseid desc
)A
ON A.houseid = h.id
WHERE h.farmid=%s;`, his_date, farmid, farmid)
		dt, err := db.GetAll(sql)
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			list := dt.List()
			/*if len(list) > 0 {
				for k, item := range list {
					houseid := gconv.String(item["houseid"])
					json_str := redis.GetHouseSummary(houseid)
					if json_str != "" {
						house_item := gconv.Map(json_str)
						list[k]["pig_num_total"] = house_item["pig_num_total"]
						list[k]["pig_num"] = house_item["pig_num"]
					}
				}
			}*/
			res["data"] = list
			res["count"] = dt.Len()
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) ExportHouseSummarySort(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := ""
	if begin != "" {
		where += fmt.Sprintf(" and his.his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his.his_date<='%s'", end)
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		sql := fmt.Sprintf(`SELECT A.farmname,h.housename,A.feed,A.water,A.max_feed,A.pig_num,A.pig_num_total,A.avg_feed,A.low_standard,A.standard,A.high_standard,A.day,A.per,A.his_date FROM v_house h
LEFT JOIN (
SELECT v.farmname,v.houseid,v.housename,
sum(day_use_feed_auto+day_use_feed_man) AS feed,
sum(day_use_water_auto+day_use_water_man) as water,
sum(max_feed) as max_feed,
sum(his.pig_num) as pig_num,
sum(his.pig_num) as pig_num_total,
avg(his.avg_feed) as avg_feed,
avg(his.low_standard) as low_standard,
avg(his.standard) as standard,
avg(his.high_standard) as high_standard,
avg(his.day) as day,
sum(day_use_feed_auto+day_use_feed_man)/sum(max_feed)*100 as per,
his.his_date as his_date 
FROM v_device v
INNER JOIN t_hzfgw_node_status_his his ON v.device_addr = his.addr %s
WHERE v.farmid=%s and mode!=0
GROUP BY v.houseid,v.housename,his.his_date
ORDER BY feed desc,water desc,v.houseid desc
)A
ON A.houseid = h.id
WHERE h.farmid=%s ORDER BY A.houseid ASC,A.his_date ASC;`, where, id, id)
		dt, err := db.GetAll(sql)
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
			r.Response.WriteJson(res)
		} else {
			//数据正常导出

			f := excelize.NewFile()
			defer func() {
				if err := f.Close(); err != nil {
					g.Log().Line(true).Error(err)
				}
			}()

			// 创建一个工作表
			index, err := f.NewSheet("Sheet1")
			if err != nil {
				g.Log().Line(true).Error(err)
			}

			//样式
			style_header, _ := f.NewStyle(&excelize.Style{
				Fill:      excelize.Fill{Type: "pattern", Color: []string{"#4958b9"}, Pattern: 1},
				Font:      &excelize.Font{Color: "#ffffff", Bold: true},
				Alignment: &excelize.Alignment{Vertical: "center", Horizontal: "center"},
			})
			style_yellow_font, _ := f.NewStyle(&excelize.Style{
				Font: &excelize.Font{Color: "#FF8010"},
			})
			style_yellow_light_font, _ := f.NewStyle(&excelize.Style{
				Font: &excelize.Font{Color: "#FFB800"},
			})
			style_green_font, _ := f.NewStyle(&excelize.Style{
				Font: &excelize.Font{Color: "#05982E"},
			})

			//列宽
			f.SetColWidth("Sheet1", "A", "J", 20)

			// 标题
			f.SetCellValue("Sheet1", "A1", "场区")
			f.SetCellValue("Sheet1", "B1", "单元")
			f.SetCellValue("Sheet1", "C1", "日龄")
			f.SetCellValue("Sheet1", "D1", "采食日期")
			f.SetCellValue("Sheet1", "E1", "存栏")
			f.SetCellValue("Sheet1", "F1", "总采食(kg)")
			f.SetCellValue("Sheet1", "G1", "头均采食(kg)")
			f.SetCellValue("Sheet1", "H1", "采食状况")
			f.SetCellValue("Sheet1", "I1", "头均低区间(kg)")
			f.SetCellValue("Sheet1", "J1", "头均正常区间(kg)")
			f.SetCellValue("Sheet1", "K1", "头均高区间(kg)")
			f.SetCellValue("Sheet1", "L1", "饮水量(L)")

			f.SetCellStyle("Sheet1", "A1", "A1", style_header)
			f.SetCellStyle("Sheet1", "B1", "B1", style_header)
			f.SetCellStyle("Sheet1", "C1", "C1", style_header)
			f.SetCellStyle("Sheet1", "D1", "D1", style_header)
			f.SetCellStyle("Sheet1", "E1", "E1", style_header)
			f.SetCellStyle("Sheet1", "F1", "F1", style_header)
			f.SetCellStyle("Sheet1", "G1", "G1", style_header)
			f.SetCellStyle("Sheet1", "H1", "H1", style_header)
			f.SetCellStyle("Sheet1", "I1", "I1", style_header)
			f.SetCellStyle("Sheet1", "J1", "J1", style_header)
			f.SetCellStyle("Sheet1", "K1", "K1", style_header)
			f.SetCellStyle("Sheet1", "L1", "L1", style_header)

			list := dt.List()
			if len(list) > 0 {
				count := 0
				for k, v := range list {
					count++
					//行数限制
					if count > 1048000 {
						break
					}

					f.SetCellValue("Sheet1", fmt.Sprintf("A%d", k+2), gconv.String(v["farmname"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("B%d", k+2), gconv.String(v["housename"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("C%d", k+2), fmt.Sprintf("%d", gconv.Int(v["day"])))
					f.SetCellValue("Sheet1", fmt.Sprintf("D%d", k+2), gconv.String(v["his_date"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("E%d", k+2), gconv.String(v["pig_num"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("F%d", k+2), fmt.Sprintf("%.3f", gconv.Float32(v["feed"])))
					f.SetCellValue("Sheet1", fmt.Sprintf("G%d", k+2), fmt.Sprintf("%.3f", gconv.Float32(v["avg_feed"])))
					var low_standard, high_standard, avg_feed float32
					low_standard = gconv.Float32(v["low_standard"])
					high_standard = gconv.Float32(v["high_standard"])
					avg_feed = gconv.Float32(v["avg_feed"])
					var health, feed_str string
					if low_standard <= avg_feed && avg_feed <= high_standard {
						//正常采食
						health = "good"
					} else {
						if low_standard > avg_feed {
							//低采食
							health = "low"
						} else if high_standard < avg_feed {
							//高采食
							health = "high"
						}
					}
					if health == "low" {
						f.SetCellStyle("Sheet1", fmt.Sprintf("H%d", k+2), fmt.Sprintf("H%d", k+2), style_yellow_font)
						feed_str = "↓采食量低"
					} else if health == "good" {
						f.SetCellStyle("Sheet1", fmt.Sprintf("H%d", k+2), fmt.Sprintf("H%d", k+2), style_green_font)
						feed_str = "采食量达标"
					} else if health == "high" {
						f.SetCellStyle("Sheet1", fmt.Sprintf("H%d", k+2), fmt.Sprintf("H%d", k+2), style_yellow_light_font)
						feed_str = "↑采食量高"
					}
					f.SetCellValue("Sheet1", fmt.Sprintf("H%d", k+2), feed_str)

					f.SetCellValue("Sheet1", fmt.Sprintf("I%d", k+2), fmt.Sprintf("%.3f", low_standard))
					f.SetCellValue("Sheet1", fmt.Sprintf("J%d", k+2), fmt.Sprintf("%.3f", low_standard)+" - "+fmt.Sprintf("%.3f", high_standard))
					f.SetCellValue("Sheet1", fmt.Sprintf("K%d", k+2), fmt.Sprintf("%.3f", high_standard))

					f.SetCellValue("Sheet1", fmt.Sprintf("L%d", k+2), fmt.Sprintf("%.3f", gconv.Float32(v["water"])))
				}
			}

			// 设置工作簿的默认工作表
			f.SetActiveSheet(index)
			f.Write(r.Response.Writer)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
		r.Response.WriteJson(res)
	}
	r.ExitAll()
}

func (a *farm) GetUsers(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()

	farmid := gconv.String(params["farmid"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		r, err := db.GetAll(fmt.Sprintf("SELECT * FROM v_user WHERE userid in (SELECT userid FROM t_user_farm WHERE farmid=%s);", farmid))
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			list := r.List()

			res["data"] = list
			res["count"] = len(list)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}
func (a *farm) SetUsers(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path

	farmid := gconv.String(params["farmid"])
	userids := gconv.String(params["userids"])
	delete(params, "userids")
	if dao.CheckApiPermission(url, r.Method, current_user) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if tx, err := db.Begin(); err == nil {
			_, err = tx.Model("t_user_farm").Where("farmid=?", farmid).Delete()
			if err == nil {
				if userids != "" {
					var _list gdb.List
					_userids := gstr.Split(userids, ",")
					for _, userid := range _userids {
						_item := gdb.Map{
							"userid":      userid,
							"farmid":      farmid,
							"create_date": gtime.Now().String(),
							"create_user": current_user,
						}
						_list = append(_list, _item)
					}

					if len(_list) > 0 {
						_, err = tx.Model("t_user_farm").Data(_list).Save()
					}
				}
			}

			if err != nil {
				tx.Rollback()
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				tx.Commit()
				res["code"] = 0
				res["msg"] = "保存成功"
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) TodayFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		data := g.Map{}
		today := gtime.Now().Format(common.DATE_FORMAT)
		sql := fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s ) AND his_date='%s' ", id, today)
		dt, err := db.GetOne(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			data = dt.Map()
			res["data"] = data
			res["count"] = 1
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) MonthFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		data := g.Map{}
		begin := gtime.Now().Format("Y-m-01")
		today := gtime.Now().Format(common.DATE_FORMAT)
		sql := fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s ) AND  his_date>='%s' AND his_date<='%s'; ", id, begin, today)
		dt, err := db.GetOne(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			data = dt.Map()
			res["data"] = data
			res["count"] = 1
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) SumFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		data := g.Map{}
		begin := gtime.Now().Format("Y-m-01")
		today := gtime.Now().Format(common.DATE_FORMAT)
		sql := ""
		if id != "" {
			sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS month_use_feed_auto,sum(day_use_feed_man) AS month_use_feed_man,sum(day_use_water_auto) AS month_use_water_auto,sum(day_use_water_man) AS month_use_water_man FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s ) AND  his_date>='%s' AND his_date<='%s'; ", id, begin, today)
		} else {
			if dao.IsAdmin(userid) || dao.IsService(userid) {
				sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS month_use_feed_auto,sum(day_use_feed_man) AS month_use_feed_man,sum(day_use_water_auto) AS month_use_water_auto,sum(day_use_water_man) AS month_use_water_man FROM t_hzfgw_node_status_his WHERE  his_date>='%s' AND his_date<='%s'; ", begin, today)
			} else {
				sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS month_use_feed_auto,sum(day_use_feed_man) AS month_use_feed_man,sum(day_use_water_auto) AS month_use_water_auto,sum(day_use_water_man) AS month_use_water_man FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s') )  AND  his_date>='%s' AND his_date<='%s'; ", userid, begin, today)
			}
		}

		dt, err := db.GetOne(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			data["month"] = dt.Map()
		}

		today = gtime.Now().Format(common.DATE_FORMAT)
		//sql=fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s ) AND his_date='%s' ",id,today)

		if id != "" {
			sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s ) AND his_date='%s' ", id, today)
		} else {
			if dao.IsAdmin(userid) || dao.IsService(userid) {
				sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE  his_date='%s' ", today)
			} else {
				sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s') ) AND his_date='%s' ", userid, today)
			}
		}
		dt, err = db.GetOne(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			data["day"] = dt.Map()
		}

		res["data"] = data
		res["count"] = 1
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) DaySumFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := ""

	if begin != "" {
		where += fmt.Sprintf(" and his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his_date<='%s'", end)
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		sql := ""
		if id != "" {
			sql = " SELECT sum(max_feed) AS max_feed,sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,sum(pig_num) as pig_num,his_date " +
				fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s ) ", id) + where +
				" GROUP BY his_date ORDER BY his_date asc;"
		} else {

			if dao.IsAdmin(userid) || dao.IsService(userid) {
				sql = " SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man,sum(pig_num) as pig_num ,his_date " +
					" FROM t_hzfgw_node_status_his where 1=1 " + where +
					" GROUP BY his_date ORDER BY his_date asc;"
			} else {
				sql = " SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man,sum(pig_num) as pig_num ,his_date " +
					fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s') ) ", userid) + where +
					" GROUP BY his_date ORDER BY his_date asc;"
			}
		}
		dt, err := db.GetAll(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["data"] = dt.List()
			res["count"] = dt.Len()
		}

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) ExportDaySumFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := ""

	if begin != "" {
		where += fmt.Sprintf(" and his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his_date<='%s'", end)
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		sql := ""
		if id != "" {
			sql = " SELECT sum(max_feed) AS max_feed,sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date " +
				fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s ) ", id) + where +
				" GROUP BY his_date ORDER BY his_date asc;"
		} else {

			if dao.IsAdmin(userid) || dao.IsService(userid) {
				sql = " SELECT sum(max_feed) AS max_feed,sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date " +
					" FROM t_hzfgw_node_status_his where 1=1 " + where +
					" GROUP BY his_date ORDER BY his_date asc;"
			} else {
				sql = " SELECT sum(max_feed) AS max_feed,sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date " +
					fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s') ) ", userid) + where +
					" GROUP BY his_date ORDER BY his_date asc;"
			}
		}
		dt, err := db.GetAll(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
			r.Response.WriteJson(res)
		} else {
			//数据正常导出
			f := excelize.NewFile()
			defer func() {
				if err := f.Close(); err != nil {
					g.Log().Line(true).Error(err)
				}
			}()

			// 创建一个工作表
			index, err := f.NewSheet("Sheet1")
			if err != nil {
				g.Log().Line(true).Error(err)
			}

			//样式
			style_header, _ := f.NewStyle(&excelize.Style{
				Fill:      excelize.Fill{Type: "pattern", Color: []string{"#4958b9"}, Pattern: 1},
				Font:      &excelize.Font{Color: "#ffffff", Bold: true},
				Alignment: &excelize.Alignment{Vertical: "center", Horizontal: "center"},
			})

			style_yellow_font, _ := f.NewStyle(&excelize.Style{
				Font: &excelize.Font{Color: "#FFB800"},
			})
			style_green_font, _ := f.NewStyle(&excelize.Style{
				Font: &excelize.Font{Color: "#05982E"},
			})

			//列宽
			f.SetColWidth("Sheet1", "A", "D", 20)

			// 标题
			f.SetCellValue("Sheet1", "A1", "日期")
			f.SetCellValue("Sheet1", "B1", "目标采食量(kg)")
			f.SetCellValue("Sheet1", "C1", "总采食量(kg)")
			f.SetCellValue("Sheet1", "D1", "总饮水量(L)")
			f.SetCellStyle("Sheet1", "A1", "A1", style_header)
			f.SetCellStyle("Sheet1", "B1", "B1", style_header)
			f.SetCellStyle("Sheet1", "C1", "C1", style_header)
			f.SetCellStyle("Sheet1", "D1", "D1", style_header)

			list := dt.List()
			if len(list) > 0 {
				count := 0
				for k, v := range list {
					count++
					//行数限制
					if count > 1048000 {
						break
					}

					feed := gconv.Float32(v["day_use_feed_auto"]) + gconv.Float32(v["day_use_feed_man"])
					water := gconv.Float32(v["day_use_water_auto"]) + gconv.Float32(v["day_use_water_man"])
					max_feed := gconv.Float32(v["max_feed"])
					f.SetCellValue("Sheet1", fmt.Sprintf("A%d", k+2), gconv.String(v["his_date"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("B%d", k+2), common.FloatToStringTrimEndZero(max_feed, 2))
					f.SetCellValue("Sheet1", fmt.Sprintf("C%d", k+2), common.FloatToStringTrimEndZero(feed, 2))
					if max_feed > feed {
						f.SetCellStyle("Sheet1", fmt.Sprintf("C%d", k+2), fmt.Sprintf("C%d", k+2), style_yellow_font)
					} else {
						f.SetCellStyle("Sheet1", fmt.Sprintf("C%d", k+2), fmt.Sprintf("C%d", k+2), style_green_font)
					}
					f.SetCellValue("Sheet1", fmt.Sprintf("D%d", k+2), common.FloatToStringTrimEndZero(water, 2))

				}
			}

			// 设置工作簿的默认工作表
			f.SetActiveSheet(index)

			f.Write(r.Response.Writer)
		}

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
		r.Response.WriteJson(res)
	}

	r.ExitAll()
}

func (a *farm) ExportDayAvgFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := ""

	if begin != "" {
		where += fmt.Sprintf(" and his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his_date<='%s'", end)
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		sql := ""
		if id != "" {
			sql = " SELECT sum(max_feed) AS max_feed,sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date " +
				fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s ) ", id) + where +
				" GROUP BY his_date ORDER BY his_date asc;"
		} else {

			if dao.IsAdmin(userid) || dao.IsService(userid) {
				sql = " SELECT sum(max_feed) AS max_feed,sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date " +
					" FROM t_hzfgw_node_status_his where 1=1 " + where +
					" GROUP BY his_date ORDER BY his_date asc;"
			} else {
				sql = " SELECT sum(max_feed) AS max_feed,sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date " +
					fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s') ) ", userid) + where +
					" GROUP BY his_date ORDER BY his_date asc;"
			}
		}
		dt, err := db.GetAll(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
			r.Response.WriteJson(res)
		} else {
			//获取猪只数量
			var pig_num_total int
			pig_num_total = 0
			json_str := redis.GetFarmSummary(id)
			if json_str != "" {
				item := gconv.Map(json_str)
				pig_num_total = gconv.Int(item["pig_num_total"])
			}

			//数据正常导出
			f := excelize.NewFile()
			defer func() {
				if err := f.Close(); err != nil {
					g.Log().Line(true).Error(err)
				}
			}()

			// 创建一个工作表
			index, err := f.NewSheet("Sheet1")
			if err != nil {
				g.Log().Line(true).Error(err)
			}

			//样式
			style_header, _ := f.NewStyle(&excelize.Style{
				Fill:      excelize.Fill{Type: "pattern", Color: []string{"#4958b9"}, Pattern: 1},
				Font:      &excelize.Font{Color: "#ffffff", Bold: true},
				Alignment: &excelize.Alignment{Vertical: "center", Horizontal: "center"},
			})

			//列宽
			f.SetColWidth("Sheet1", "A", "C", 20)

			// 标题
			f.SetCellValue("Sheet1", "A1", "日期")
			f.SetCellValue("Sheet1", "B1", "头均采食量(kg)")
			f.SetCellValue("Sheet1", "C1", "头均饮水量(L)")
			f.SetCellStyle("Sheet1", "A1", "A1", style_header)
			f.SetCellStyle("Sheet1", "B1", "B1", style_header)
			f.SetCellStyle("Sheet1", "C1", "C1", style_header)

			list := dt.List()
			if len(list) > 0 {
				count := 0
				for k, v := range list {
					count++
					//行数限制
					if count > 1048000 {
						break
					}

					var avg_feed float32
					var avg_water float32
					feed := gconv.Float32(v["day_use_feed_auto"]) + gconv.Float32(v["day_use_feed_man"])
					water := gconv.Float32(v["day_use_water_auto"]) + gconv.Float32(v["day_use_water_man"])
					if pig_num_total > 0 {
						avg_feed = feed / float32(pig_num_total)
						avg_water = water / float32(pig_num_total)
					} else {
						avg_feed = 0
						avg_water = 0
					}
					f.SetCellValue("Sheet1", fmt.Sprintf("A%d", k+2), gconv.String(v["his_date"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("B%d", k+2), common.FloatToStringTrimEndZero(avg_feed, 2))
					f.SetCellValue("Sheet1", fmt.Sprintf("C%d", k+2), common.FloatToStringTrimEndZero(avg_water, 2))

				}
			}

			// 设置工作簿的默认工作表
			f.SetActiveSheet(index)

			f.Write(r.Response.Writer)
		}

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
		r.Response.WriteJson(res)
	}

	r.ExitAll()
}

func (a *farm) SumMode(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	//where:= ""

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {

		/*data := g.List{}
		for i := 0; i < 7; i++ {
			sql := ""
			if id != "" {
				sql = fmt.Sprintf("SELECT count(1) AS num FROM t_hzfgw_node_para WHERE addr in (SELECT device_addr FROM v_device WHERE farmid=%s) AND `mode`=%d;", id, i)
			} else {
				if dao.IsAdmin(userid) || dao.IsService(userid) {
					sql = fmt.Sprintf("SELECT count(1) AS num FROM t_hzfgw_node_para WHERE `mode`=%d;", i)
				} else {
					sql = fmt.Sprintf("SELECT count(1) AS num FROM t_hzfgw_node_para WHERE addr in (SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s')) AND `mode`=%d;", userid, i)
				}
			}
			record, err := db.GetOne(sql)
			if err != nil {
				g.Log().Line().Error(err)
				//res["code"]=-1
				//res["msg"] = err.Error()
				//break
			} else {
				if record != nil {
					item := record.Map()
					item["mode"] = i
					data = append(data, item)
				}
			}
		}*/

		sql := ""
		if id != "" {
			sql = fmt.Sprintf("SELECT sum(pig_num) as num,sum(son) as son_num,device_type,`mode` FROM v_hzgw_node WHERE addr in (SELECT device_addr FROM v_device WHERE farmid=%s) GROUP BY device_type,`mode`;", id)
		} else {
			if dao.IsAdmin(userid) || dao.IsService(userid) {
				sql = fmt.Sprintf("SELECT sum(pig_num) as num,sum(son) as son_num,device_type,`mode` FROM v_hzgw_node GROUP BY device_type,`mode`;")
			} else {
				sql = fmt.Sprintf("SELECT sum(pig_num) as num,sum(son) as son_num,device_type,`mode` FROM v_hzgw_node WHERE addr in (SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s')) GROUP BY device_type,`mode`;", userid)
			}
		}
		records, err := db.GetAll(sql)
		if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["code"] = 0
			res["data"] = records.List()
		}

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *farm) MapData(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		list := g.List{}

		farmList := dao.GetPermisFarm(userid)
		if id == "" {

		} else {
			//选择养殖场
			farmsRecords, err := dao.T_farm.GetList(fmt.Sprintf("id=%s", id))
			if err != nil {
				g.Log().Line().Error(err)
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				if len(farmsRecords) > 0 {
					farmList = append(farmList, farmsRecords[0])
				}
			}
		}

		if len(farmList) > 0 {
			for _, item := range farmList {
				farmid := gconv.String(item["id"])
				sql := " SELECT d.farmid,d.device_addr,d.alive as online,count(s.online=1 or null) as onlineNum,count(1) as deviceNum,COUNT(s.alarm>0 or null) as alarmNum FROM v_device d " +
					" LEFT JOIN t_hzfgw_node_status s on d.device_addr = s.addr " +
					fmt.Sprintf(" WHERE d.farmid = %s GROUP BY d.farmid,d.device_addr ,d.alive", farmid)
				dtList, err := db.GetAll(sql)
				if err != nil {
					res["code"] = -1
					res["msg"] = err.Error()
				} else {
					all_onlineNum := 0
					all_deviceNum := 0
					all_alarmNum := 0
					if dtList.Len() > 0 {
						for _, dt := range dtList {
							online := gconv.Int(dt["online"])
							onlineNum := gconv.Int(dt["onlineNum"])
							deviceNum := gconv.Int(dt["deviceNum"])
							alarmNum := gconv.Int(dt["alarmNum"])
							if online > 0 {
								all_onlineNum += onlineNum
							}
							all_deviceNum += deviceNum
							all_alarmNum += alarmNum
						}
					}
					item["onlineNum"] = all_onlineNum
					item["deviceNum"] = all_deviceNum
					item["alarmNum"] = all_alarmNum
				}

				list = append(list, item)
			}
		}

		res["data"] = list
		res["count"] = len(list)

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}
